package com.javaee.wordtree.service;

import com.javaee.wordtree.entity.*;
import com.javaee.wordtree.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class StoryGenerationService {
    
    @Resource
    private DeepseekService deepseekService;
    
    @Resource
    private StoryTemplateMapper storyTemplateMapper;
    
    @Resource
    private StoryPageMapper storyPageMapper;
    
    /**
     * 生成完整的交互式故事树
     */
    @Transactional
    public StoryTemplate generateCompleteStory(List<String> words, String difficulty, String theme) {
        log.info("开始生成完整故事树, 单词: {}, 难度: {}, 主题: {}", words, difficulty, theme);
        
        // 1. 创建故事模板
        StoryTemplate template = new StoryTemplate();
        template.setTitle(generateStoryTitle(theme, words));
        template.setDescription("基于单词学习的交互式故事");
        template.setDifficultyLevel(difficulty);
        template.setWordList(words);
        template.setTheme(theme);
        storyTemplateMapper.insert(template);
        
        // 2. 生成故事开始页面
        StoryPage rootPage = generateStoryIntroduction(template.getId(), words);
        storyPageMapper.insert(rootPage);
        
        // 3. 递归生成故事分支（最多3层深度）
        generateStoryBranches(template.getId(), rootPage, words, 1, 3);
        
        // 4. 更新模板的总页数
        int totalPages = storyPageMapper.findByTemplateId(template.getId()).size();
        template.setTotalPages(totalPages);
        storyTemplateMapper.updateById(template);
        
        log.info("故事生成完成，模板ID: {}, 总页数: {}", template.getId(), totalPages);
        return template;
    }
    
    /**
     * 递归生成故事分支
     */
    private void generateStoryBranches(Long templateId, StoryPage parentPage, List<String> words, int currentDepth, int maxDepth) {
        if (currentDepth >= maxDepth || parentPage.getChoices() == null || parentPage.getChoices().isEmpty()) {
            return;
        }
        
        for (int i = 0; i < parentPage.getChoices().size(); i++) {
            String choice = parentPage.getChoices().get(i);
            
            // 生成下一个页面
            StoryPage nextPage = generateStoryBranch(templateId, parentPage, i, choice, words, currentDepth, maxDepth);
            if (nextPage != null) {
                storyPageMapper.insert(nextPage);
                
                // 如果不是结局页面，继续递归生成
                if (!nextPage.getIsEnding()) {
                    generateStoryBranches(templateId, nextPage, words, currentDepth + 1, maxDepth);
                }
            }
        }
    }
    
    /**
     * 生成故事介绍页面
     */
    private StoryPage generateStoryIntroduction(Long templateId, List<String> words) {
        String prompt = buildIntroPrompt(words);
        
        try {
            DeepseekResponse response = deepseekService.callDeepseekApi(prompt).block();
            if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                String content = response.getChoices().get(0).getMessage().getContent();
                
                return parseStoryContent(templateId, null, null, content, 1);
            }
        } catch (Exception e) {
            log.error("生成故事介绍失败", e);
        }
        
        return null;
    }
    
    /**
     * 生成故事分支页面
     */
    private StoryPage generateStoryBranch(Long templateId, StoryPage parentPage, int choiceIndex, 
                                        String choice, List<String> words, int currentDepth, int maxDepth) {
        
        boolean isLastLevel = (currentDepth >= maxDepth - 1);
        String prompt = buildBranchPrompt(parentPage, choice, words, isLastLevel);
        
        try {
            DeepseekResponse response = deepseekService.callDeepseekApi(prompt).block();
            if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                String content = response.getChoices().get(0).getMessage().getContent();
                
                StoryPage page = parseStoryContent(templateId, parentPage.getId(), choiceIndex, content, currentDepth + 1);
                if (isLastLevel) {
                    page.setIsEnding(true);
                    page.setChoices(new ArrayList<>()); // 结局页面没有选择
                }
                return page;
            }
        } catch (Exception e) {
            log.error("生成故事分支失败", e);
        }
        
        return null;
    }
    
    /**
     * 解析AI生成的故事内容
     */
    private StoryPage parseStoryContent(Long templateId, Long parentPageId, Integer choiceIndex, String content, int pageNumber) {
        StoryPage page = new StoryPage();
        page.setTemplateId(templateId);
        page.setParentPageId(parentPageId);
        page.setChoiceIndex(choiceIndex);
        page.setPageNumber(pageNumber);
        
        // 解析英文和中文内容
        String[] sections = content.split("(?i)Chinese:|中文:");
        if (sections.length >= 2) {
            page.setEnglishContent(extractEnglishContent(sections[0]));
            page.setChineseContent(extractChineseContent(sections[1]));
        } else {
            page.setEnglishContent(content);
            page.setChineseContent("");
        }
        
        // 解析选择项
        List<String> choices = extractChoices(content);
        page.setChoices(choices);
        page.setIsEnding(choices.isEmpty());
        
        // 生成场景图片（异步处理）
        generateSceneImageAsync(page);
        
        return page;
    }
    
    private String extractEnglishContent(String section) {
        return section.replaceAll("(?i)English:", "").trim();
    }
    
    private String extractChineseContent(String section) {
        String[] parts = section.split("(?i)Choices:|选择:");
        return parts[0].trim();
    }
    
    private List<String> extractChoices(String content) {
        List<String> choices = new ArrayList<>();
        String[] lines = content.split("\n");
        
        for (String line : lines) {
            line = line.trim();
            if (line.matches("^\\d+\\.\\s*.+")) {
                String choice = line.replaceFirst("^\\d+\\.\\s*", "");
                choices.add(choice);
            }
        }
        
        return choices;
    }
    
    private void generateSceneImageAsync(StoryPage page) {
        // 异步生成图片，这里可以使用 @Async 注解或线程池
        // 暂时简化处理
        try {
            String imagePrompt = extractImagePrompt(page.getEnglishContent());
            String base64Image = callImageGenerationService(imagePrompt);
            page.setSceneImageBase64(base64Image);
        } catch (Exception e) {
            log.warn("生成场景图片失败: {}", e.getMessage());
        }
    }
    
    private String extractImagePrompt(String content) {
        // 从故事内容中提取适合生成图片的描述
        String prompt = content.length() > 100 ? content.substring(0, 100) : content;
        return prompt + ", 8-bit, simple, colorful, single scene, cute, clear composition";
    }
    
    private String callImageGenerationService(String prompt) {
        // 调用图片生成服务
        // 这里需要实现具体的图片生成逻辑
        return null;
    }
    
    private String generateStoryTitle(String theme, List<String> words) {
        return String.format("The %s Adventure - Learning: %s", 
            theme, String.join(", ", words.subList(0, Math.min(3, words.size()))));
    }
    
    private String buildIntroPrompt(List<String> words) {
        return "You are an advanced English learning story AI. Generate a creative and engaging story introduction that uses ALL the following words at least once: " 
            + String.join(", ", words) + ". "
            + "Highlight the target words by enclosing them in asterisks (*). "
            + "First write the story in English, then provide a Chinese translation. "
            + "At the end, provide 3 numbered choices for the next action (choices only in English). "
            + "Format:\n\nEnglish:\n<Story introduction in English>\n\nChinese:\n<故事介绍的中文翻译>\n\n"
            + "Choices:\n1. <Option 1>\n2. <Option 2>\n3. <Option 3>";
    }
    
    private String buildBranchPrompt(StoryPage parentPage, String choice, List<String> words, boolean isEnding) {
        String prompt = "Continue the interactive English story based on the previous content and user choice.\n"
            + "Previous story: " + parentPage.getEnglishContent() + "\n"
            + "User chose: " + choice + "\n"
            + "Continue to use the learning words: " + String.join(", ", words) + "\n\n";
            
        if (isEnding) {
            prompt += "Write a satisfying ending for this story branch. "
                + "Format:\n\nEnglish:\n<Ending in English>\n\nChinese:\n<结局的中文翻译>";
        } else {
            prompt += "Write the next part of the story and provide 2-3 new choices. "
                + "Format:\n\nEnglish:\n<Next part in English>\n\nChinese:\n<下一部分的中文翻译>\n\n"
                + "Choices:\n1. <Option 1>\n2. <Option 2>\n3. <Option 3>";
        }
        
        return prompt;
    }
}